#include<QtGui>
#include "counter.h"
Counter::Counter(const QString & f, const int h, const int w){
	setFixedSize(w,h);
	filename = f;
	QFile data(filename);
	if (data.open(QFile::ReadOnly)){
		QTextStream fin(&data);
		QString line;
		do{
			line = fin.readLine();
			if (line.isNull()) break;
			QStringList s = line.split(":");
			hash[s[0]] = s[1].toInt();
		}while(!line.isNull());
		if (hash.size())
		cur = hash.begin().key();
		else cur = "some";
		data.close();
	}
	update();
}
void Counter::add(const int k){hash[cur] += k; update();}
void Counter::reset(){hash[cur] = 0; update();}
void Counter::save(){
	QFile data(filename);
	if (data.open(QFile::WriteOnly)){
		QTextStream fout(&data);
		QHash<QString, int>::const_iterator i = hash.begin();
    	while (i != hash.end()) {
	    	fout <<i.key() << ":" << i.value() << endl;
        	++i;
    	}
    	fout.flush();
    	data.close();
    }
}
void Counter::loadCnf(const QString & s){save(); cur = QString("%1.%2").arg(s).arg("txt"); if (!hash[cur]) hash[cur] = 0; update();}
void Counter::paintEvent ( QPaintEvent * event ){
	QPainter painter(this);
	painter.setBrush(Qt::white);
	painter.setPen(Qt::gray);
	painter.drawRect(0,0,width()-1,height()-1);
	QString s = QString("%1").arg(hash[cur]);
	painter.setFont(QFont("Arial",30));
	painter.drawText(1,1,width()-2,height()-2, Qt::AlignVCenter | Qt::AlignHCenter, QString("%1").arg(hash[cur]));
}
